/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
<template>
  <div class="page-wrapper">
    <s-header :name="`${type == 'add' ? '添加收货地址' : '修改收货地址'}`"></s-header>
    <van-address-edit
      :address-info="addressInfo"
      :show-delete="type != 'add'"
      show-set-default
      :show-area="false"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import { reactive, onMounted, toRefs } from 'vue'
import sHeader from '@/components/MyHeader'
import { addAddress, modifyAddress, deleteAddress, getAddressDetail } from '@/service/axios-services'
import { useRoute, useRouter } from 'vue-router'
export default {
  components: {
    sHeader
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      type: 'add',
      addressId: '',
      addressInfo: {},
      from: route.query.from
    })

    onMounted(async () => {
      const { addressId, type, from } = route.query
      state.addressId = addressId
      state.type = type
      state.from = from || ''
      if (type != 'add') {
        const { data } = await getAddressDetail(addressId)
        state.addressInfo = {
          id: data.id,
          name: data.name,
          tel: data.phone,
          addressDetail: data.address,
          isDefault: data.defaultAddress
        }
      }
    })

    const onSave = async (content) => {
      const params = {
        name: content.name,
        phone: content.tel,
        address: content.addressDetail,
        defaultAddress: content.isDefault,
      }
      if (state.type != 'add') {
        params['id'] = state.addressId
      }
      await state.type == 'add' ? addAddress(params) : modifyAddress(params)
      router.back()
    }

    const onDelete = async () => {
      await deleteAddress(state.addressId)
      router.back()
    }

    return {
      ...toRefs(state),
      onSave,
      onDelete
    }
  }
}
</script>
<style>
  .van-button {
    background: #EF3965;
    border-color: #EF3965;
    color:white;
  }
</style>